clc;clear;clearvars;
addpath('CEC2008\');
global initial_flag

NS = 100;   % 种群数
dim = 500;   % 种群维度
s = 5;    % 子空间的数目,设定为5,10
upper_bound = [100,100,100,5,600,32,1];    % 搜索区间
lower_bound = [-100,-100,-100,-5,-600,-32,-1];
bestYhistory = [];    % 保存每次迭代的最佳值

for func_num = 1

    initial_flag = 0;    % 换一个函数initial_flag重置为0
    sample_x = lhsdesign(NS, dim).*(upper_bound(func_num) - lower_bound(func_num)) + lower_bound(func_num).*ones(NS, dim);    % 生成NS个种群,并获得其评估值
    sample_y = benchmark_func(sample_x,func_num);
    [best_y, bestIndex] = min(sample_y);    % 获取全局最小值以及对应的种群
    best_x = sample_x(bestIndex,:);

    for i0 = 1 : 50     % 迭代50次

        index = randperm(dim);      % 随机划分子空间
        for i1 = 1 : s
            index1 = index(((i1 - 1) * (dim / s) + 1) : (i1 * (dim / s)));
            sub_x = sample_x(:,index1);
            sub_x = SaNSDE(sub_x, sample_y, best_x, index1, 400 / s, dim / s, lower_bound(func_num), upper_bound(func_num), @(x)benchmark_func(x,func_num));%401*100
            sample_x(:,index1) = sub_x;
            sample_y = benchmark_func(sample_x,func_num);
            [~, bestIndex] = min(sample_y);    % 获取全局最小值以及对应的种群
            best_x = sample_x(bestIndex,:);
        end

        [worse_y, worseIndex] = max(sample_y);    % 获取全局最大值以及对应的种群
        randIndex = randi(NS);
        while randIndex == bestIndex || randIndex == worseIndex
            randIndex = randi(NS);     % 随机获取一个值
        end
        [worseX,worseY] = NSDE(sample_x(worseIndex,:), NS, 40, s, -2, 2, 0.9, @(x)benchmark_func(x,func_num));% 120*100
        [bestX,bestY] = NSDE(sample_x(bestIndex,:), NS, 40, s, -2, 2, 0.9, @(x)benchmark_func(x,func_num));% 权重向量在[-2,2]之间搜寻
        [randX,randY] = NSDE(sample_x(randIndex,:), NS, 40, s, -2, 2, 0.9, @(x)benchmark_func(x,func_num));
        if worseY < best_y
            sample_x(worseIndex,:) = worseX;
            sample_y(worseIndex,:) = worseY;
        end
        if bestY < best_y
            sample_x(bestIndex,:) = bestX;
            sample_y(bestIndex,:) = bestY;
        end
        if randY < best_y
            sample_x(randIndex,:) = randX;
            sample_y(randIndex,:) = randY;
        end

        [best_y, bestIndex] = min(sample_y);    % 获取全局最小值以及对应的种群
        best_x = sample_x(bestIndex,:);
        bestYhistory = [bestYhistory;best_y];

        disp(i0);
    end
end
plot(bestYhistory);